package com.emep.changzhi.analyse.service.statistics;


import com.emep.changzhi.analyse.entity.aqi.*;
import com.emep.changzhi.analyse.entity.basics.SysAqiLevel;
import com.emep.changzhi.analyse.entity.outlet.SysOutletInfo;
import com.emep.changzhi.analyse.repository.aqi.*;
import com.emep.changzhi.analyse.repository.basics.SysAqiLevelRepository;
import com.emep.changzhi.analyse.service.outlet.SysOutletInfoService;
import com.emep.changzhi.analyse.utils.DateTimeUtil;
import com.emep.changzhi.analyse.utils.MapUtils;
import com.emep.changzhi.analyse.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.validation.constraints.Null;
import java.text.ParseException;
import java.util.*;

/**
 * @author lqj
 * @version V1.0
 * @Description: 统计今年到目前为止的重污染(优良)天数、和去年同期的重污染(优良)天数,去年全年的重污染(优良)天数
 * @date 2018/4/12
 */
@Service
public class DayofGoodAndHeavyPollutionService {

    @Resource
    private AqiCityRepository aqiCityRepository;
    @Resource
    private SysAqiLevelRepository aqiLevelRepository;

    @Resource
    private AqiNumberOfDaysRepository aqiNumberOfDaysRepository;

   @Resource
    private DataAqiInfoRepository dataAqiInfoRepository;



    private static final Logger logger = LoggerFactory.getLogger(SysOutletInfoService.class);


    /**
     *
     *某段时间内某城市的重污染天数或优良天数
     *
     * @param
     * @return
     * @throws Exception
     */
    public int dayOfSoFar(String city,String starttime,String endtime,String level) {
        int day=0;

        //城市名称
//        String city = payload.get("cityCode") != null ? payload.get("cityCode").toString():"" ;
//        //开始时间
//        String starttime = payload.get("startDate")!= null ? payload.get("startDate").toString():"";
//          //结束时间
//        String endtime = payload.get("endDate")!= null ? payload.get("endDate").toString():"";
//
//        //重污染or优良
//        String level = payload.get("day")!= null ? payload.get("day").toString():"";




        try {
            /**
             * 统计某时间段内的重污染(优良)天数
             */
            if(!StringUtils.isEmpty(city) && !StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)){

                String start=String.valueOf( DateTimeUtil.stringToDate(starttime,DateTimeUtil.DATETIME_DEFAULT_FORMAT).getTime());
                String end= String.valueOf( DateTimeUtil.stringToDate(endtime,DateTimeUtil.DATETIME_DEFAULT_FORMAT).getTime());
                Sort sort = new Sort(Sort.Direction.DESC, "update1");
                //获取某时间段内的某城市AreaAqiMoniter列表
               List<AreaAqiMoniter> areaAqiMoniter= aqiCityRepository.findAll(new Specification<AreaAqiMoniter>(){
                    @Override
                    public javax.persistence.criteria.Predicate toPredicate(Root<AreaAqiMoniter> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                        javax.persistence.criteria.Predicate p1 = null;
                        javax.persistence.criteria.Predicate p2 = null;
                        javax.persistence.criteria.Predicate p3 = null;
                            //大于或等于传入时间
                            p1 = criteriaBuilder.greaterThanOrEqualTo(root.get("update1").as(String.class),start );
                            //小于或等于传入时间
                            p2 = criteriaBuilder.lessThanOrEqualTo(root.get("update1").as(String.class), end);

                        //站点名称
                        p3 = criteriaBuilder.equal(root.get("areaId").as(String.class), city);
                        query.where(criteriaBuilder.and(p1,p2,p3));
                        return query.getRestriction();
                    }
                },sort);
                //获取指定level的aqi
                SysAqiLevel  sysAqiLevel=aqiLevelRepository.findSysAqiLevelBylevel(level);
                int aqi=Integer.valueOf(sysAqiLevel.getAqi());

                if(areaAqiMoniter.size()>0){
                    //优良天数指小于良aqi
                    if(sysAqiLevel.equals("良")){
                        for (int i=0;i<areaAqiMoniter.size();i++){
                            int j=Integer.valueOf (areaAqiMoniter.get(i).getAqi());

                            if(j<aqi){
                                day++;
                            }
                        }
                    }
                    if(sysAqiLevel.equals("重度污染")){
                        //重污染天数指大于重污染aqi
                        for (int i=0;i<areaAqiMoniter.size();i++){
                            int j=Integer.valueOf (areaAqiMoniter.get(i).getAqi());

                            if(j>=aqi){
                                day++;
                            }
                        }

                }


                }


            }

        }catch (Exception e){
            logger.error(e.getLocalizedMessage());
        }
        return day;
    }


    /**
     *
     *去年全年的重污染(优良)天数
     *
     * @param
     * @return
     * @throws Exception
     */
    public int dayOfLastYear(String cityCode){

        int day=0;


        try {
            Calendar a=Calendar.getInstance();
            int year=a.get(Calendar.YEAR) - 1;

            AqiNumberOfDays aqiNumberOfDays= aqiNumberOfDaysRepository.findByYearAndAreaCode(String.valueOf(year),cityCode);


            Date start=DateTimeUtil.stampToStringSaveYear();
            Date end=DateTimeUtil.stampToStringEndYear();


        }catch (Exception e){
            logger.error(e.getLocalizedMessage());
        }




        return day;

    }



     /**
     *
     *按照小时数据（6参数）排序国控站点
     *
     * @param payload
     * @return
     * @throws Exception
     */
    public   List<DataAqiInfo> rankingSites(Map<String, Object> payload){

        List<DataAqiInfo> dataAqiInfoList =null;

        //污染物名称
        String pollutionName = payload.get("pollutionName") != null ? payload.get("pollutionName").toString():"" ;

        try {

            Sort.Order order = new Sort.Order(Sort.Direction.DESC, "timePoint");
            Sort.Order order1 = new Sort.Order(Sort.Direction.DESC, pollutionName);
            List<Sort.Order> sortList = new ArrayList<Sort.Order>();
            sortList.add(order);
            sortList.add(order1);
            Sort sort = new Sort(sortList);



//            Sort sort = new Sort(Sort.Direction.DESC, "timePoint", pollutionName);
            dataAqiInfoList =dataAqiInfoRepository.findAll(sort);


        }catch (Exception e){
            logger.error(e.getLocalizedMessage());
        }




        return dataAqiInfoList;

    }


}
